<template>
  <div class="table-page-search-wrapper">
    <a-card :bordered="false">
      <a-form layout="inline">
        <a-row :gutter="48">
          <a-col :md="8" :sm="12">
            <a-form-item label="开课院系">
              <a-select :disabled="selectMenu.yxList.length === 1" allowClear v-model="queryParam.kkyxm" @change="yxChange" showSearch :filterOption="filterOption">
                <a-select-option v-for="i in selectMenu.yxList" :key="i.id" :value="i.dwh">{{ i.dwh }} {{ i.dwmc }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="12">
            <a-form-item label="开课学年">
              <a-select allowClear v-model="queryParam.kkxn">
                <a-select-option v-for="i in TYPE0125" :key="i.id" :value="i.code">{{ i.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <template v-if="advanced">
            <a-col :md="8" :sm="12">
              <a-form-item label="开课学期">
                <a-select allowClear v-model="queryParam.kkxqm">
                  <a-select-option v-for="i in TYPE0072" :key="i.id" :value="i.code">{{ i.name }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="12">
              <a-form-item label="教师姓名">
                <a-input v-model.trim="queryParam.jsxm"/>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="12">
              <a-form-item label="教室">
                <a-input v-model="queryParam.classroomNo"/>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="12">
              <a-form-item label="课程名称">
                <a-select allowClear v-model="queryParam.kcbm" showSearch :filterOption="filterOption">
                  <a-select-option v-for="i in selectMenu.courseList" :key="i.id" :value="i.kch">{{i.kch}}-{{ i.kcmc }}</a-select-option>
                </a-select>
              </a-form-item>
              <!-- <a-form-item label="课程名称">
                <a-input v-model="queryParam.kcmc"/>
              </a-form-item> -->
            </a-col>
          </template>
        </a-row>
        <a-row>
          <span class="table-page-search-submitButtons" >

          <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
          <a-button v-if="inPkTime" v-hasPermission="'pkxx:add'" type="primary" @click="toAdd" style="margin:0 10px">添加排课</a-button>
          <a-upload
            v-hasPermission="'pkxx:add'"
            name="file"
            :action="uploadUrl"
            :showUploadList="false"
            :headers="{
                Authorization: $store.state.account.token
              }"
            :beforeUpload="beforeUpload"
            @change="handleChange">
              <a-button type="primary">导入</a-button>
            </a-upload>
          <a-button type="primary" @click="exportExcel" style="margin:0 10px">导出</a-button>
          <a-button type="primary" v-hasPermission="'pkxx:add'" v-if="inPkTime" @click="batchDelete">删除</a-button>
          <a type="link" :href="tplHref" v-hasPermission="'pkxx:add'">下载模板</a>
          <a @click="advanced = !advanced" style="margin-left: 8px">
              {{ advanced ? '收起' : '展开' }}
              <a-icon :type="advanced ? 'up' : 'down'"/>
            </a>
          </span>
        </a-row>
      </a-form>
    </a-card>

    <a-card :bordered="false" style="margin-top: 10px">
      <s-table
        v-if="initDone"
        ref="table"
        size="default"
        rowKey="id"
        :columns="columns"
        :data="loadData"
        :alert="{show: true}"
        :rowSelection="options.rowSelection"
        :pageSize="parameter.pageSize"
        :pageNum="parameter.pageNum"
        :scroll="{ x: 2200 }"
      >
        <span slot="serial" slot-scope="text, record, index">
          {{ index + 1 + (parameter.pageNo - 1) * parameter.pageSize }}
        </span>
        <template slot="operation" slot-scope="a,b">
          <a v-if="inPkTime" v-hasPermission="'pkxx:update'" @click="toEdit(b)">修改</a>
          <a-divider v-if="inPkTime" v-hasPermission="'pkxx:update'" type="vertical" />
          <a-dropdown>
            <a class="ant-dropdown-link">
              更多 <a-icon type="down"/>
            </a>
            <a-menu slot="overlay">
              <a-menu-item v-if="b.sftksq == 0" v-hasPermission="'tksq:add'">
                <a @click="toTransfer(b)">调课</a>
              </a-menu-item>
              <a-menu-item v-if="b.sftksq == 1" v-hasPermission="'tksq:add'">
                <span>调课审核中</span>
              </a-menu-item>
              <a-menu-item>
                <a @click="showStudents(b)">查看听课学生名单</a>
              </a-menu-item>
            </a-menu>
          </a-dropdown>

        </template>
      </s-table>
    </a-card>

    <transfer-course ref="transfer" :visible="transferVisible" @cancel="transferVisible = false"  @refresh="$refs.table.refresh(false)"/>
    <students-list ref="students" :visible="studentsVisible" @cancel="studentsVisible = false" />

  </div>
</template>

<script>
import { STable } from '~'
import { mapState } from 'vuex'
import transferCourse from './transferCourse'
import studentsList from './studentsList'
import searchMixin from '@/utils/searchRemain'

export default {
  mixins: [ searchMixin ],
  data () {
    return {
      selectedRowKeys: [],
      options: {
        alert: { show: true, clear: () => { this.selectedRowKeys = [] } },
        rowSelection: {
          selectedRowKeys: this.selectedRowKeys,
          onChange: this.onSelectChange
        }
      },
      uploadUrl:`${process.env.SERVICE_URL}foster/pkxx/imp`,
      tplHref:`${process.env.IMG_URL}tpl/排课信息导入模板.xlsx`,
      advanced: true,
      queryParam: {},
      columns: [
        {
          title: '序号',
          scopedSlots: { customRender: 'serial' }
        },
        {
          title: '课程代码',
          dataIndex: 'kcbm',
          width:120
        },
        {
          title: '课程名称',
          dataIndex: 'kcmc',
          width:150
        },
        {
          title: '课程类型',
          dataIndex: 'kclbmc',
          width:150
        },
        {
          title: '上课年级',
          dataIndex: 'sknj',
          width:150
        },
        {
          title: '班号',
          dataIndex: 'jxbh',
          width:100
        },
        {
          title: '教师',
          dataIndex: 'rkjsmc'
        },
        {
          title: '周类型',
          dataIndex: 'skzlxmc'
        },
        {
          title: '上课周',
          dataIndex: 'skzmc'
        },
        {
          title: '开始周',
          dataIndex: 'ksz'
        },
        {
          title: '结束周',
          dataIndex: 'jsz'
        },
        {
          title: '开始课节',
          dataIndex: 'kskj'
        },
        {
          title: '结束课节',
          dataIndex: 'jskj'
        },
        {
          title: '学时',
          dataIndex: 'xs'
        },
        {
          title: '已选人数',
          dataIndex: 'tkrs'
        },
        {
          title: '最大选课人数',
          dataIndex: 'xkrsxd'
        },
        {
          title: '最小选课人数',
          dataIndex: 'xkrsxdMin'
        },
        {
          title: '开课院系',
          dataIndex: 'pydw'
        },
        {
          title: '开课学期',
          dataIndex: 'kkxqmc'
        },
        {
          title: '教室',
          dataIndex: 'classroomNo'
        },
        {
          title: '教室类型',
          dataIndex: 'jslxmc'
        },
        {
          title: '教室位置',
          dataIndex: 'xqmc'
        },
        {
          title: '操作',
          dataIndex: 'operation',
          width: 130,
          scopedSlots: { customRender: 'operation' },
          fixed: 'right'
        }
      ],
      parameter: {
        pageNo: 1,
        pageSize: 10
      },
      loadData: parameter => {
        this.parameter = parameter
        parameter.pageNum = parameter.pageNo
        let params = Object.assign(this.queryParam, parameter)
        return this.$api.cultivate.arrangeCourseList(params).then(res => {
          return {
            data: res.data.rows,
            pageNo: parameter.pageNo,
            pageSize: parameter.pageSize,
            totalPage: Math.ceil(res.data.total / parameter.pageSize),
            totalCount: res.data.total
          }
        })
      },
      selectMenu: {
        yxList: [], // 院系
      },
      detailVisible: false,
      confirmLoading: false,
      courseInfo: {},
      transferVisible: false,
      studentsVisible: false,
      initDone: false,
      inPkTime: true
    }
  },
  components: {STable, transferCourse, studentsList},
  computed: {
    ...mapState({
      TYPE0125: state => state.app['TYPE0125'],
      TYPE0072: state => state.app['TYPE0072']
    })
  },
  created () {
    this.$store.dispatch('app/sysInfo', true).then(data => {
      if ( +new Date() > +data.pkjssj  ||  +new Date() < +data.pkkssj ) {
        this.inPkTime = false
      }
    })
    this.$store.dispatch('app/setDictionary', 'TYPE0072')
    this.$store.dispatch('app/setDictionary', 'TYPE0125')
    // this.initSelectMenu()
  },
  methods: {
    onSelectChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    initSelectMenu (noFrist = 0) {
      let allRequest = [
        this.$api.base.collegeAll(),
        this.$store.dispatch('app/sysInfo')
      ]
      Promise.all(allRequest).then(res => {
        this.selectMenu = {
          yxList: res[0].data
        }
        if (!noFrist) {
          this.$set(this.queryParam, 'kkxqm', res[1].currentSemester)
          this.$set(this.queryParam, 'kkxn', res[1].schoolYear)
        }
        if(this.selectMenu.yxList && this.selectMenu.yxList.length == 1){
          this.$set(this.queryParam, 'kkyxm', this.selectMenu.yxList[0].dwh)
        }
        this.initDone = true
      })
    },
    beforeUpload (file) {
      if (file.name.split('.')[1] !== 'xlsx') {
        this.$message.error('只支持.xlsx格式')
        return false
      }
    },
    handleChange (info) {
      if (info.file.status === 'done') {
        this.$message.success('导入成功');
        this.$refs.table.refresh(false)
      } else if (info.file.status === 'error') {
        this.$message.error(info.file.response.msg || '导入失败');
      }
    },
    filterOption (value, op) {
      return op.componentOptions.children[0].text.indexOf(value) !== -1
    },
    toAdd () {
      this.$router.push('/cultivate/arrangeCourse/add')
    },
    batchDelete () {
      if (!this.selectedRowKeys.length) {
        this.$message.warning('请选择需要删除的排课信息')
        return
      }
      this.$confirm({
        title: '确定删除所选中的排课吗?',
        content: '当您点击确定按钮后，这些记录将会被删除',
        centered: true,
        onOk: () => {
          let ids = this.selectedRowKeys.join(',')
          this.$api.cultivate.pkxxDelete(ids).then(() => {
            this.$message.success('删除成功')
            this.selectedRowKeys = []
            this.$refs.table.refresh(false)
            this.$refs.table.clearSelected()
          })
        },
        onCancel: () => {
        }
      })
    },
    yxChange (code) {
      this.$set(this.queryParam, 'kcbm', '')
      if (code) {
        this.kcLoading = true
        this.$api.cultivate.courseAll({kcssyxm: code}).then(res => {
          this.$set(this.selectMenu, 'courseList', res.data)
        }).finally(() => {
          this.kcLoading = false
        })
      } else {
        this.$set(this.selectMenu, 'courseList', [])
      }
    },
    showTransfer (c) {
      this.$refs.transfer.pkxxId = c.id
      this.$refs.transfer.note = c.note
      this.transferVisible = true
      // this.$api.cultivate.arrangeCourseDetail(c.id).then(res => {
      //   this.$refs.transfer.form.setFieldsValue(res.data)
      // })
    },
    toEdit (c) {
      this.$router.push(`/cultivate/arrangeCourse/add?id=${c.id}`)
    },
    toTransfer(c) {
      this.$router.push(`/cultivate/arrangeCourse/tk?id=${c.id}`)
    },
    showStudents (c) {
      this.studentsVisible = true
      this.$refs.students.pkxxId = c.id
      this.$nextTick(() => {
        this.$refs.students.$refs.table.refresh(true)
      })
    },
    exportExcel () {
      let params = this.selectedRowKeys.length ? {ids: this.selectedRowKeys.join(',')} : {...this.queryParam}
      delete params.pageNum
      this.$export('/foster/pkxx/export', params)
    }
  }
}
</script>
